//
//  MutipleAccountViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/16.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire
import SnapKit
import ObjectMapper
import Kingfisher
class MutipleAccountViewController: UIViewController {
    var timeAlert:TWLAlertView?
    var index:Int?
    
    fileprivate var securetyAlertView:MutipleAccountSecurityView?
    var phoneNum:String?
    var password:String?
    lazy var itemArray : [MutipleAccountModel] = [MutipleAccountModel]()
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getMutipleAccountData()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        // self.tableView.separatorStyle = .none
        
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        
        self.tableView.register(UINib.init(nibName: "MutipleAccountCell", bundle: nil), forCellReuseIdentifier: "MutipleAccount")
    }
    
    fileprivate func getMutipleAccountData(){
        var parameter = [String:String].init()
        parameter["cellPhoneNumber"] = self.phoneNum
        Alamofire.request(MutipleAccountUrl, method: .get, parameters: parameter, headers: nil).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    
                    guard  dict["State"] as! NSString == "OK" else{
                        return
                    }
                    guard  let resultArray : NSArray = dict["Result"] as? NSArray else{
                        return
                    }
                    self.itemArray = Mapper<MutipleAccountModel>().mapArray(JSONObject: resultArray)!
                    self.tableView.reloadData()
                }
            }else{
                
            }
        }
    }
}
extension MutipleAccountViewController : UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.itemArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : MutipleAccountCell = tableView.dequeueReusableCell(withIdentifier: "MutipleAccount") as! MutipleAccountCell
        let model = self.itemArray[indexPath.row]
        cell.idCardLabel.text = Tool.securityWithIDCard(model.LealPersonIDCard!)
        let personUrl = model.Portrait ?? ""
        cell.nameLabel.text = model.Name
        cell.headerView.kf.setImage(with: URL.init(string: ImageUrlPrefix + personUrl), placeholder: UIImage.init(named: "au_header"), options: nil, progressBlock: nil, completionHandler: nil)
        cell.headerView.layer.cornerRadius = 15
        cell.headerView.layer.masksToBounds = true
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.index = indexPath.row
        self.setupSecurityAlert()
    }
    fileprivate func setupSecurityAlert(){
        
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : MutipleAccountSecurityView = MutipleAccountSecurityView.init(frame: CGRect(x: 0, y: 0, width: 295, height: 216))
        custom.cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
       // custom.phoneTextField.addTarget(self, action: #selector(phoneTextFieldClick(_:)), for: .valueChanged)
        custom.phoneTextField.text = self.phoneNum
        //custom.phoneTextField.isEnabled = false
        custom.securityTextField.addTarget(self, action: #selector(securityTextFieldClick(_:)), for: .editingChanged)
        custom.securityButton.addTarget(self, action: #selector(getSecurityCode), for: .touchUpInside)
        custom.makeSureButton.addTarget(self, action: #selector(makeSureButtonClick), for: .touchUpInside)
        self.securetyAlertView = custom
        self.timeAlert?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 295, height: 216))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
    }
    
    @objc fileprivate func securityTextFieldClick(_ titleF:UITextField){
        guard let username = self.securetyAlertView?.phoneTextField.text, username.count > 0 else {
            WWError("用户名为空")
            return
        }
           self.securetyAlertView?.makeSureButton.isEnabled = true
        self.securetyAlertView?.makeSureButton.backgroundColor = UIColor(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
    }
//    @objc fileprivate func phoneTextFieldClick(_ textF:UITextField){
//        if textF.text?.count == 11 && self.securetyAlertView?.securityTextField.text?.count == 4 {
//            self.securetyAlertView?.makeSureButton.isEnabled = true
//            self.securetyAlertView?.makeSureButton.backgroundColor = UIColor(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
//        }
//
//
//    }
    @objc fileprivate func makeSureButtonClick(){
        self.timeAlert?.cancleView()
        let model = self.itemArray[index!]
        guard let varificationCode = self.securetyAlertView?.securityTextField.text,varificationCode.count > 0 else {
            QWTextonlyHud("未输入验证码", target: self.view)
            return
        }
        guard (model.LealPersonIDCard != nil) else {
            return
        }
        
        var parameter = [String:String].init()
        parameter["flag"] = "agentapply"
        parameter["cellPhoneNumber"] = self.phoneNum
        parameter["verifycode"] = varificationCode
        
        Alamofire.request(VidifySecurityUrl, method: .get, parameters: parameter, headers: nil).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    
            guard  dict["State"] as! NSString == "OK" else{
                QWTextonlyHud("验证码错误,请重新输入！", target: self.view)
                return
            }
            self.dealWithMutipleAccount(varificationCode: varificationCode,card: model.UserID!)
            }
            
            }
        }
    }
    fileprivate func dealWithMutipleAccount(varificationCode:String,card:String){
        var parameter = [String:String].init()
        parameter["IDCard"] = card
        parameter["cellPhoneNumber"] = self.phoneNum
        parameter["verificationCode"] = varificationCode
        parameter["passWord"] = self.password
        
        Alamofire.request(DealWithMutipleAccountUrl, method: .get, parameters: parameter, headers: nil).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    
                    guard  dict["State"] as! NSString == "OK" else{
                        self.dismiss(animated: true, completion: {
                            
                        })
                        return
                    }
                    self.doLoginAction()
                }
            }else{
                
            }
        }
    }
    @objc func doLoginAction() {
        guard (self.password != nil) else {
            return
        }
        QWTextonlyHud("正在登录...", target: self.view)
        UserModel.login(username:self.phoneNum!, password: self.password!) { (response) in
            if response.success {
                QWHudDiss(self.view)
                (UIApplication.shared.delegate as! AppDelegate).setTags(WWUser.sharedInstance.accountId)
                RemoteNotificationModel.registerClient({ (response) in
                    if response.success {
                        
                    }
                    else {
                    }
                })
                
            let tabbar = WWTabBarController()
    UIApplication.shared.delegate?.window!?.rootViewController = tabbar
            }
            else {
                self.dismiss(animated: true, completion: {
                    
                })
            }
        }
    }
    @objc fileprivate func getSecurityCode(){
        guard let phoneNumber = self.securetyAlertView?.phoneTextField.text, phoneNumber.count > 0 else {
            WWError("请输入手机号码后再获取")
            return
        }
    self.securetyAlertView?.securityButton.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: (self.securetyAlertView?.securityButton.backgroundColor!)!, countColor: UIColor.gray)
        
        UserModel.requestSecurityCode(phoneNumber: phoneNumber, flag: FlagType.agentapply) { (response) in
            if response.success {
                #if DEBUG
                    WWInform(response.value ?? "好像是空的")
                #else
                #endif
            }
            else {
                WWInform(response.message)
            }
        }
    }
    @objc fileprivate func cancelButtonClick(){
        self.timeAlert?.cancleView()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}
